import 'dart:convert';
import 'package:short_video_app/entity/user_entity.dart';
import 'package:short_video_app/utils/sharepreferences_util.dart';


class UserManager {
  static UserEntity? userEntity;

  /// 工厂构造方法，用于实现单例模式
  factory UserManager() => _instance;
  /// 初始化 _instance
  static final UserManager _instance = UserManager._();
  UserManager._() {
    _init();
  }
  void _init() async {
    final userString = await SharedPreferencesUtil.getString("user");
    if (userString != null) {
      UserManager.userEntity = UserEntity.fromJson(jsonDecode(userString));
    }
  }
  /// 保存当前登录用户信息
  Future saveUserInfo(UserEntity entity) async {
    userEntity = entity;
    await SharedPreferencesUtil.setData("user", jsonEncode(userEntity?.toJson()));
    await SharedPreferencesUtil.setData("token", userEntity?.token);
  }

  Future<String?> getToken() async {
    return await SharedPreferencesUtil.getString("token");
  }

  Future clearUserInfo() async {
    await SharedPreferencesUtil.removeAllData();
  }
}
